package cn.com.jonpad.config;

import cn.com.jonpad.vo.Utils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * 因为次认证中心会提供User信息，所以也是资源服务器。
 *  <p>参看：https://github.com/spring-guides/tut-spring-security-and-angular-js/blob/master/oauth2-vanilla/README.adoc</p>
 * @author Jon Chan
 * @date 2018/9/10 15:38
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
	@Override
	public void configure(HttpSecurity http) throws Exception {
		//@off format
		http
				.csrf().disable()
				// 如果需要则创建Session
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
				//.maximumSessions(1).expiredUrl("/errror")
				.and()
				// 路径匹配规则配置.匹配所有
				.requestMatchers().anyRequest()
				.and()
				// 允许匿名用户，并包含角色“ROLE_ANONYMOUS”
				.anonymous()
				.and()
				// 配置访问限制的URL路径
				.authorizeRequests()
				//.antMatchers("/product/**").access("#oauth2.hasScope('select') and hasRole('ROLE_USER')")
				//配置order访问控制，必须认证过后才可以访问
				.antMatchers("/order/**").authenticated();
	}
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {
		// 指示这些资源上仅允许基于令牌的身份验证的标志
		resources.resourceId(Utils.DEMO_RESOURCE_ID).stateless(true);
	}
}
